package cn.ydw.community.controller;

import cn.ydw.community.entity.DiscussPost;
import cn.ydw.community.entity.PageDTO;
import cn.ydw.community.service.LikeService;
import cn.ydw.community.service.UserService;
import cn.ydw.community.service.impl.ElasticService;
import cn.ydw.community.util.CommunityConstant;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
public class SearchController implements CommunityConstant {

    @Autowired
    private ElasticService elasticService;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    @GetMapping("/search")
    public
    String toSearch(String keyword, Model model, Page page) throws IOException {
        page.setSize(8);
        // 查询的是返回的JSON字符串
        List<DiscussPost> list = elasticService.search(keyword, (int) page.offset(), (int) page.getSize(), model);
        long totalHits = (long) model.getAttribute("totalRows");
        page.setTotal(totalHits);
        page.setPages(page.getPages());
        PageDTO pageDTO = new PageDTO(page);
        pageDTO.pageDTO();
        pageDTO.setPath("/search?keyword=" + keyword);
        model.addAttribute("page", page);
        model.addAttribute("pagedto", pageDTO);
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if (list != null){
            for (DiscussPost post : list) {
                Map<String, Object> map = new HashMap<>();
                // 帖子
                map.put("post", post);
                // 作者
                map.put("user", userService.selectUserById(Integer.valueOf(post.getUserId())));
                // 点赞数量
                map.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId()));

                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPost", discussPosts);
        model.addAttribute("keyword", keyword);
        return "/site/search";
    }

}
